package com.paireach.szwolaiyun.sz_util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

public class Md5 {

    /**
     * 计算指定文件的MD5
     *
     * @param f
     * @return
     */
    public static String getFileMD5(File f) throws Exception {
        InputStream fis;
        byte[] buffer = new byte[1024];
        int numRead = 0;
        MessageDigest md5;
        fis = new FileInputStream(f);
        md5 = MessageDigest.getInstance("MD5");
        while ((numRead = fis.read(buffer)) > 0) {
            md5.update(buffer, 0, numRead);
        }
        fis.close();
        return CommonString.byte2HexStr(md5.digest());
    }

    /**
     * 计算指定文件名的文件的MD5
     *
     * @param filename
     * @return
     */
    public static String getFileMD5(String filename) throws Exception {
        InputStream fis;
        byte[] buffer = new byte[1024];
        int numRead = 0;
        MessageDigest md5;

        fis = new FileInputStream(filename);
        md5 = MessageDigest.getInstance("MD5");
        while ((numRead = fis.read(buffer)) > 0) {
            md5.update(buffer, 0, numRead);
        }
        fis.close();
        return CommonString.byte2HexStr(md5.digest());
    }

    /**
     * 计算指定的字符串的MD5
     * @param string
     * @return
     * @throws Exception
     */
    public static String getStringMD5(String string) throws Exception{
        byte[] hash;
        hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }
}